
// Include the necessary modules.
var sys = require( "sys" );
var http = require( "http" );
 
// Include the Controller layer.
var controller = require( "./controller.js" );
 
 
// ---------------------------------------------------------- //
// ---------------------------------------------------------- //
 
 
// Create an instance of the HTTP server.
var server = http.createServer(
    function( request, response ){
 
 
        // Our controller is an instance of the Event Emitter. We
        // will be using this to listen to controller events. We
        // could have handled this with Success and Fail callbacks;
        // but, I wanted an excuse to experiment with the Event
        // stuff as it appears to be quite central to Node.js.
 
 
        // Bind to the "Data" event. This is the event that gets
        // emitted when the controller has data to return.
        controller.on(
            "data",
            function( data ){
 
                // Set the 200-OK header.
                response.writeHead(
                    200,
                    { "Content-Type": "text/plain" }
                );
 
                // Return the response from the API request.
                response.write( JSON.stringify( data ) );
 
                // Close the request.
                response.end();
 
            }
        );
 
 
        // Bind to the "Error" event. This is the event that gets
        // triggered when a success response cannot be returned. This
        // will either be because an error occurred; or, because the
        // record request by the API cannot be found.
        //
        // NOTE: For our simple purposes, we are going to assume that
        // the errorType is simply an HTTP Status Code. This will
        // keep our logic very simple for this exploration.
        controller.on(
            "error",
            function( errorType ){
 
                // Set the error header (is really just an HTTP
                // status for our purposes).
                response.writeHead(
                    errorType,
                    { "Content-Type": "text/plain" }
                );
 
                // Close the request.
                response.end();
 
            }
        );
 
 
        // Pass the request off to the controller.
        controller.handle( request, response );
 
 
    }
);
 
// Point the server to listen to the given port for incoming
// requests.
server.listen( 8080 );
 
 
// ---------------------------------------------------------- //
// ---------------------------------------------------------- //
 
 
// Write debugging information to the console to indicate that
// the server has been configured and is up and running.
sys.puts( "Server is running on 8080" );